<?php
error_reporting(0);
define('SABLOG_ROOT', true);
@header("content-Type: text/html; charset=UTF-8");
ob_start();

// 允许程序在 register_globals = off 的环境下工作
$onoff = function_exists('ini_get') ? ini_get('register_globals') : get_cfg_var('register_globals');
if ($onoff != 1) {
	@extract($_POST, EXTR_SKIP);
	@extract($_GET, EXTR_SKIP);
}

// 去除转义字符
function sax_stripslashes(&$array) {
	if (is_array($array)) {
		foreach ($array as $k => $v) {
			$array[$k] = sax_stripslashes($v);
		}
	} else if (is_string($array)) {
		$array = stripslashes($array);
	}
	return $array;
}

@set_magic_quotes_runtime(0);
// 判断 magic_quotes_gpc 状态
if (@get_magic_quotes_gpc()) {
    $_GET = sax_stripslashes($_GET);
    $_POST = sax_stripslashes($_POST);
}

$step = $_GET['step'] ? $_GET['step'] : $_POST['step'];
$php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
$action = $_GET['action'] ? $_GET['action'] : $_POST['action'];
$configfile = '../config.php';

$sqlfile = 'install.sql';
if(!is_readable($sqlfile)) {
	exit('数据库文件不存在或者读取失败');
}
$fp = fopen($sqlfile, 'rb');
$sql = fread($fp, 2048000);
fclose($fp);

if ($step) {
	@include($configfile);
	//@include('../include/func_db_mysql.php');
	@include('../include/class/mysql.class.php');
	$DB = new DB_MySQL;
	$DB->connect($servername, $dbusername, $dbpassword, $dbname, $usepconnect);
	unset($servername, $dbusername, $dbpassword, $usepconnect);
}
$wp_db_prefix = addslashes($_GET['wp_db_prefix'] ? $_GET['wp_db_prefix'] : $_POST['wp_db_prefix']);
$posturl = $wp_db_prefix ? 'wp_db_prefix='.$wp_db_prefix : '';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>WordPress to SaBlog-X 转换脚本</title>
<style type="text/css">
body {
	margin: 20px;
	line-height: 140%;
	color: #000000;
	font: 14px Georgia, Verdana, Tahoma;
	background-color: #cdd6dd;
	text-align: center;
}
a {
	color: #333399; 
	text-decoration: none;
}
a:hover {
	color: #CC0000; 
}
td {
	font: 14px Georgia, Verdana, Tahoma;
	line-height: 160%;
	color: #000000;
}
div {
	font: 14px Georgia, Verdana, Tahoma;
	line-height: 160%;
	color: #000000;
}
#main {
	background-color: #fff;
	text-align: left;
	padding: 20px;
	width: 600px;
	border: 1px solid #ccc;
	margin-bottom: 20px;
}
.title {
	font-size: 18px;
	font-weight: bold;
}
form {
	margin: 0px;
	padding: 0px;
}
.formfield {
	font: 14px Georgia, Verdana, Tahoma;
	font-weight: bold;
	background-color: #fff;
	padding: 3px;
	border: 1px solid #BFBFBF;
	margin-right: 10px;
}
.formbutton {
	font: 14px Georgia, Verdana, Tahoma;
	font-weight: bold;
	padding: 3px;
}
</style>
</head>
<body>
<div id="main">
  <form method="post" action="<?php echo $php_self.'?'.$posturl;?>">
    <p class="title">WordPress to SaBlog-X 转换向导</p>
    <hr noshade="noshade" />
<?php
if (!$step || $step == '1') {
?>
    <p class="title">第一步:转换须知</p>
	<ol>
	<li>本程序只用于 <b>WordPress 2.3.x</b> 转换到 <b>SaBlog-X 1.6</b></li>
	<li>本程序只转换分类、文章、评论、用户、友情链接、站点统计数据。其他部分数据可以通过重建数据生成.</li>
	<li>转换文章的时候,所属分类只选择WordPress的第一个分类作为SaBlog-X的所属分类.</li>
	<li>转换不会对 WordPress 的数据进行任何操作!所以可以不备份 WordPress 的数据.</li>
	<li>转换过程也可以看作是全新安装 SaBlog-X 1.6. 因此可以不用事先安装 SaBlog-X 1.6.</li>
	<li>转换完毕后一定删除本脚本!</li>
	<li>转换过程中千万不能关闭浏览器!</li>
	<li>为简化步骤,不做过多的判断!因此请尽量按照程序的要求操作.</li>
	<li>没有遵照步骤提示操作造成的一切后果自己承担,本程序作者不会负任何责任!</li>
	</ol>
    <p>&nbsp;</p>
    <p>请输入WordPress的数据表前缀: <input type="text" name="wp_db_prefix" value="wp_" /></p>
    <p>&nbsp;</p>
    <p>点击下一步就开始升级操作!</p>
    <hr noshade="noshade" />
    <p align="right">
      <input type="hidden" name="step" value="2" />
      <input class="formbutton" type="submit" value="下一步" />
    </p>
<?php
} elseif ($step == '2') {
?>
    <p class="title">第二步:建立数据表</p>
    <p>本步骤建立 SaBlog-X V1.6 的数据表</p>
	<p>
<?php
	runquery($sql);
?>
    </p>
    <p>&nbsp;</p>
	<p>点击下一步就开始把 WordPress 的数据分步骤转移到刚才建立的 Sablog-X 数据表中.</p>
    <hr noshade="noshade" />
    <p align="right">
      <input type="hidden" name="step" value="3" />
      <input class="formbutton" type="submit" value="下一步" />
    </p>
<?php
} elseif ($step == '3') {
?>
    <p class="title">第三步:转移数据</p>
	<ol>
	<li>用户数据</li>
	<li>分类数据</li>
	<li>文章数据</li>
	</ol>
	<p>
<?php
	///////////
	$query = $DB->query("SELECT ID,user_login,user_pass,user_email,user_url,user_registered FROM {$wp_db_prefix}users");
	while ($wpuser = $DB->fetch_array($query)) {
		$wpuserext = $DB->fetch_one_array("SELECT meta_value FROM {$wp_db_prefix}usermeta WHERE user_id='".$wpuser['ID']."' AND meta_key='{$wp_db_prefix}user_level'");
		if ($wpuserext['meta_value'] == 10) {
			$SaxGroupID = 1;
		} else {
			$SaxGroupID = 3;
		}
		if ($wpuser['url']) {
			$SaxUserUrl = addslashes($wpuser['user_url']);
		} else {
			$SaxUserUrl = addslashes($wpuser['user_email']);
		}
		$SaxRegDateline = strtotime($wpuser['user_registered']);
		$SaxUserID = intval($wpuser['ID']);
		$SaxUserName = addslashes($wpuser['user_login']);
		$SaxPassWord = addslashes($wpuser['user_pass']);

		$DB->query("INSERT INTO {$db_prefix}users (userid,username,password,url,regdateline,groupid) VALUES ('$SaxUserID','$SaxUserName','$SaxPassWord','$SaxUserUrl','$SaxRegDateline','$SaxGroupID')");
	}
	echo '用户转换完毕<br />';
	//////////////
	$query = $DB->query("SELECT t.*, tt.* FROM {$wp_db_prefix}terms AS t INNER JOIN {$wp_db_prefix}term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy IN ('category') ORDER BY t.name ASC");
	while ($wpcate = $DB->fetch_array($query)) {
		$SaxCateID = intval($wpcate['term_id']);
		$SaxCateArticles = intval($wpcate['count']);
		$SaxCateName = addslashes($wpcate['name']);
		$DB->query("INSERT INTO {$db_prefix}categories (cid,name,articles) VALUES ('$SaxCateID','$SaxCateName','$SaxCateArticles')");
	}
	echo '分类转换完毕<br />';
	//////////////
	$query = $DB->query("SELECT * FROM {$wp_db_prefix}posts WHERE post_type='post'");

	while ($wppost = $DB->fetch_array($query)) {
		$SaxArticleID = intval($wppost['ID']);
		// 评论属性
		if ($wppost['comment_status'] == 'open') {
			$SaxCloseComment = 0;
		} else {
			$SaxCloseComment = 1;
		}
		// 引用属性
		if ($wppost['ping_status'] == 'open') {
			$SaxCloseTrackback = 0;
		} else {
			$SaxCloseTrackback = 1;
		}
		// 文章状态
		if ($wppost['post_status'] == 'publish') {
			$SaxVisible = 1;
		} else {
			$SaxVisible = 0;
		}
		// 内容和描述
		if ($wppost['post_excerpt']) {
			$SaxDesc = $wppost['post_excerpt'];
		} elseif (strpos($wppost['post_content'], '<!--more-->')) {
			@list($SaxDesc) = @explode('<!--more-->', $wppost['post_content']);
		} else {
			$SaxDesc = '';
		}

		$SaxDesc = addslashes($SaxDesc);
		$SaxTitle = addslashes($wppost['post_title']);
		$SaxContent = addslashes(str_replace('<!--more-->','',$wppost['post_content']));
		$SaxUID = intval($wppost['post_author']);
		$SaxDateline = strtotime($wppost['post_date']);
		$SaxComments = intval($wppost['comment_count']);
		$SaxReadPassword = addslashes($wppost['post_password']);
		$SaxAlias = addslashes($wppost['post_name']);

		//转换TAG
		$ArticleTags = $tmark = '';
		$cate = $DB->query("SELECT t.*, tt.*, tr.object_id FROM wp_terms AS t INNER JOIN wp_term_taxonomy AS tt ON tt.term_id = t.term_id INNER JOIN wp_term_relationships AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ('category', 'post_tag') AND tr.object_id IN ($SaxArticleID) ORDER BY t.name ASC");
		while ($rs = $DB->fetch_array($cate)) {
			if ($rs['taxonomy'] == 'category') {
				$SaxCid = $rs['term_id'];
			} else {
				$ArticleTags .= $tmark.$rs['name'];
				$tmark = ',';
			}
		}

		$DB->query("INSERT INTO {$db_prefix}articles (articleid,cid,uid,title,description,content,keywords,dateline,comments,closecomment,closetrackback,visible,readpassword,alias) VALUES ('$SaxArticleID','$SaxCid','$SaxUID','$SaxTitle','$SaxDesc','$SaxContent','$ArticleTags','$SaxDateline','$SaxComments','$SaxCloseComment','$SaxCloseTrackback','$SaxVisible','$SaxReadPassword','$SaxAlias')");
	}
	echo '文章转换完毕<br />';
?>
    </p>
    <p>&nbsp;</p>
	<p>点击下一步继续把 WordPress 的数据转移到 Sablog-X 的数据表中.</p>
    <hr noshade="noshade" />
    <p align="right">
      <input type="hidden" name="step" value="4" />
      <input class="formbutton" type="submit" value="下一步" />
    </p>
<?php
} elseif ($step == '4') {
?>
    <p class="title">第四步:转移数据</p>
	<ol>
	<li>评论数据</li>
	</ol>
	<p>
<?php
	///////////////////////////
	$query = $DB->query("SELECT comment_ID,comment_post_ID,comment_author,comment_author_email,comment_author_url,comment_author_IP,comment_date,comment_content,comment_approved FROM {$wp_db_prefix}comments WHERE comment_type=''");
	while ($wpcomment = $DB->fetch_array($query)) {
		$SaxCmID = intval($wpcomment['comment_ID']);
		$SaxCmAID = intval($wpcomment['comment_post_ID']);
		$SaxCmAuthor = addslashes($wpcomment['comment_author']);
		if ($wpcomment['comment_author_url']) {
			$SaxCmUrl = addslashes($wpcomment['comment_author_url']);
		} else {
			$SaxCmUrl = addslashes($wpcomment['comment_author_email']);
		}
		$SaxCmDateline = strtotime($wpcomment['comment_date']);
		//评论内容还需要处理
		$SaxCmContent = addslashes($wpcomment['comment_content']);
		$SaxCmContent = str_replace(array('<br/>','<br>','<br />'),"\r\n",$SaxCmContent);
		$SaxCmContent = html2text($SaxCmContent);

		$SaxCmIP = addslashes($wpcomment['comment_author_IP']);
		if ($wpcomment['comment_approved'] == 1) {
			$SaxCmVisible = 1;
		} else {
			$SaxCmVisible = 0;
		}

		$DB->query("INSERT INTO {$db_prefix}comments (commentid,articleid,author,url,dateline,content,ipaddress,visible) VALUES ('$SaxCmID','$SaxCmAID','$SaxCmAuthor','$SaxCmUrl','$SaxCmDateline','$SaxCmContent','$SaxCmIP','$SaxCmVisible')");
	}
	echo '评论转换完毕<br />';
?>
    </p>
    <p>&nbsp;</p>
	<p>点击下一步继续把 WordPress 的数据转移到 Sablog-X 的数据表中.</p>
    <hr noshade="noshade" />
    <p align="right">
      <input type="hidden" name="step" value="5" />
      <input class="formbutton" type="submit" value="下一步" />
    </p>
<?php
} elseif ($step == '5') {
?>
    <p class="title">第五步:转移数据</p>
	<ol>
	<li>友情链接数据</li>
	</ol>
	<p>
<?php
	$query = $DB->query("SELECT link_url,link_name,link_visible,link_notes FROM {$wp_db_prefix}links");
	while ($wplink = $DB->fetch_array($query)) {
		if ($wplink['link_visible'] == 'Y') {
			$SaxLinkVisible = 1;
		} else {
			$SaxLinkVisible = 0;
		}
		$DB->query("INSERT INTO {$db_prefix}links (name, url, note, visible) VALUES ('".addslashes($wplink['link_name'])."','".addslashes($wplink['link_url'])."','".addslashes($wplink['linkdesc'])."','$SaxLinkVisible')");
	}
	echo '友情链接转换完毕<br />';
?>
    </p>
    <p>&nbsp;</p>
	<p>数据转换完毕!点击下一步将告诉您一些注意事项(重要).</p>
    <hr noshade="noshade" />
    <p align="right">
      <input type="hidden" name="step" value="6" />
      <input class="formbutton" type="submit" value="下一步" />
    </p>
<?php
} elseif ($step == '6') {
?>
    <p class="title">第六步:注意事项</p>
    <p>已经把 WordPress 的数据,您可以将 <b>install</b> 目录删除了.别忘记了.</p>
    <p>现在您需要做的一些事情.</p>
	<ol>
	<li>到后台重新设置您的系统的配置选项.</li>
	<li>执行一次附件修复.清除一些垃圾数据使您的系统运行速度更快.</li>
	<li>执行一次清理标签的操作.将您的标签数据修复.</li>
	<li>执行一次重建数据的操作.将所有数据重新统计.否则可能有些功能不正常.</li>
	<li>执行一次更新全部缓存操作.</li>
	</ol>
    <p>&nbsp;</p>
	<p>如果上面的操作都做完而且没有出现异常情况.恭喜你.平滑转换成功!</p>
	<p>如果有问题可以给我发电子邮件!</p>
    <p><a href="../">点击这里进入首页</a></p>
    <hr noshade="noshade" />
    <p align="right"><a href="http://www.4ngel.net">Welcome to Security Angel Team</a></p>
<?php
}
?>
  </form>
</div>
<strong>Powered by SaBlog-X (C) 2003-2007 Security Angel Team</strong>
</body>
</html>
<?php

function runquery($sql) {
	global $db_prefix, $DB, $tablenum;

	$sql = str_replace("\r", "\n", str_replace(' sablog_', ' '.$db_prefix, $sql));
	$ret = array();
	$num = 0;
	foreach(explode(";\n", trim($sql)) as $query) {
		$queries = explode("\n", trim($query));
		foreach($queries as $query) {
			$ret[$num] .= $query[0] == '#' ? '' : $query;
		}
		$num++;
	}
	unset($sql);

	foreach($ret as $query) {
		$query = trim($query);
		if($query) {
			if(substr($query, 0, 12) == 'CREATE TABLE') {
				$name = preg_replace("/CREATE TABLE ([a-z0-9_]+) .*/is", "\\1", $query);
				echo '创建表 '.$name.' ... <font color="#0000EE">成功</font><br />';
				$DB->query(createtable($query));
				$tablenum++;
			} else {
				$DB->query($query);
			}
		}
	}
}

function createtable($sql) {
	$type = strtoupper(preg_replace("/^\s*CREATE TABLE\s+.+\s+\(.+?\).*(ENGINE|TYPE)\s*=\s*([a-z]+?).*$/isU", "\\2", $sql));
	$type = in_array($type, array('MYISAM', 'HEAP')) ? $type : 'MYISAM';
	return preg_replace("/^\s*(CREATE TABLE\s+.+\s+\(.+?\)).*$/isU", "\\1", $sql).
		(mysql_get_server_info() > '4.1' ? " ENGINE=$type DEFAULT CHARSET=utf8" : " TYPE=$type");
}

function html2text($content) {
	$content = preg_replace("/<style .*?<\/style>/is", "", $content);
	$content = preg_replace("/<script .*?<\/script>/is", "", $content);
	$content = preg_replace("/<br\s*\/?>/i", "\n", $content);
	$content = preg_replace("/<\/?p>/i", "\n", $content);
	$content = preg_replace("/<\/?td>/i", "\n", $content);
	$content = preg_replace("/<\/?div>/i", "\n", $content);
	$content = preg_replace("/<\/?blockquote>/i", "\n", $content);
	$content = preg_replace("/<\/?li>/i", "\n", $content);
	$content = preg_replace("/\&nbsp\;/i", " ", $content);
	$content = preg_replace("/\&nbsp/i", " ", $content); 
	$content = strip_tags($content);
	$content = preg_replace("/\&\#.*?\;/i", "", $content);
	return $content;
}
?>